layui.use(['element', 'layer', 'util', 'form', "dropdown"], function () {
    var element = layui.element;
    var layer = layui.layer;
    var util = layui.util;
    var $ = layui.$;
    var form = layui.form;
    var dropdown = layui.dropdown;
    var addAiBox; // 添加ai类型窗口
    var md = window.markdownit();

    // 初始化 highlight.js 库
    // hljs.highlightAll();



    //定义数据
    var chatData = layui.data("chatData");
    // console.log(chatData.length)
    default_chatData(chatData)


    //默认至少只有一个ai类型
    function default_chatData(chatData) {
        if (JSON.stringify(chatData) == "{}") {
            var id = uuid();
            var obj = {
                key: id,
                value: {
                    title: "AI助手",
                    remark: "解决通用问题",
                    greetings: "你好，我是AI助手，请问您需要什么帮助？",
                    data: [
                        {
                            "content": "",
                            "id": "LEMUR_AI_SYSTEM_SETTING",
                            "isSensitive": false,
                            "needCheck": false,
                            "role": "system"
                        }
                    ]
                }
            }
            layui.data("chatData", obj)

            eachList(layui.data("chatData"))
        } else {
            eachList(chatData)
        }
    }

    // 字符串整理json
    function gptStrJson(text) {
        // console.log(text)
        var str = text.replace(/\}\{/g, "},{");

        return JSON.parse(`[${str}]`)

        /* var str = text.replace(/(?<=\})(?=\{)/g, ',')
        str = str.split("}null{").join("},{")
        str = str.split("nullnull{").join("{")
        str = str.split('"code":0}null').join('"code":0}')
        str = str.split('null{"origin"').join('{"origin"')
        return JSON.parse(`[${str}]`) */
    }

    // Gpt数据字符串整理
    function gptStrObj(text) {

        // console.log(text) //data: [DONE]
        text = text.replace("data: [DONE]", "");
        const jsonStrings = text.split('\n').filter(str => str.trim() !== '');
        const jsonObjects = [];

        for (let str of jsonStrings) {
            const jsonStr = str.substr(str.indexOf('{'));
            const jsonObject = JSON.parse(jsonStr);
            jsonObjects.push(jsonObject);
        }

        // console.log(jsonObjects);
        return jsonObjects;
    }


    // 转义html后的修复
    function escape(html) {
        var str = html.split("&lt;").join("<")
        str = str.split("&gt;").join(">")
        str = str.split("&amp;").join("&")
        return str;
    }

    function escapeHTML(html) {

        var temp = document.createElement('div');
        temp.textContent = html;
        return temp.innerHTML;
    }

    // 机器人说话
    function msgUser(id, content) {
        var robMsg = $(`#${id}`)
        if (robMsg.length) {
            robMsg.find(".msg").append(escapeHTML(content))
            var message = robMsg.find(".msg").html()
            robMsg.find(".content").html((md.render(escape(message))))
        } else {
            var message = md.render(content)
            $(".message").append(`
            <li class="msg-user" id="${id}">
                <div class="head-portrait">
                    <img src="/assets/index/images/ai_yueqing.jpg" alt="">
                </div>
                <div class="layui-hide msg">${escapeHTML(content)}</div>
                <div class="content">${escape(message)}</div>
                <button class="layui-btn layui-btn-primary layui-btn-xs more-btn">
                    <i class="layui-icon layui-icon-more-vertical layui-font-12"></i>
                </button>
            </li>
            `)
        }
        hljs.highlightAll();
        BoxRoll()
    }

    // 我说话
    function msgMine(content) {
        // console.log(content)
        $(".message").append(`
            <li class="msg-mine">
                <button class="layui-btn layui-btn-primary layui-btn-xs more-btn">
                    <i class="layui-icon layui-icon-more-vertical layui-font-12"></i>
                </button>
                <pre class="content">${escapeHTML(content)}</pre>
                <div class="head-portrait">
                    <img src="/assets/index/images/wechat.jpg" alt="">
                </div>
            </li>`)
        $("#msg-content").val('')
        BoxRoll()
    }

    //生成uuid
    function uuid() {
        if (typeof crypto === 'object') {
            if (typeof crypto.randomUUID === 'function') {
                return crypto.randomUUID();
            }
            if (typeof crypto.getRandomValues === 'function' && typeof Uint8Array === 'function') {
                const callback = (c) => {
                    const num = Number(c);
                    return (num ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (num / 4)))).toString(16);
                };
                return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, callback);
            }
        }
        let timestamp = new Date().getTime();
        let perforNow = (typeof performance !== 'undefined' && performance.now && performance.now() * 1000) || 0;
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
            let random = Math.random() * 16;
            if (timestamp > 0) {
                random = (timestamp + random) % 16 | 0;
                timestamp = Math.floor(timestamp / 16);
            } else {
                random = (perforNow + random) % 16 | 0;
                perforNow = Math.floor(perforNow / 16);
            }
            return (c === 'x' ? random : (random & 0x3) | 0x8).toString(16);
        });
    };


    // 遍历左侧数据
    function eachList(data) {
        layui.each(data, function (k, v) {
            $('.list-left').prepend(`
            <li class="layui-nav-item" data-id="${k}">
                <a href="javascript:;" class="side-li">
                    <div class="side-li-img">
                        <img src="/assets/index/images/ai_yueqing.jpg" alt="">
                    </div>
                    <div class="side-li-span">
                        <p>${v.title}</p>
                        <span>${v.remark}</span>
                    </div>
                </a>
            </li>
        `);
        })
    }

    //追加更新
    function dataEdit(id, data) {
        var obj = layui.data("chatData", { key: id })
        obj.data.push(data) //追加信息
        layui.data("chatData", { key: id, value: obj })//更新信息
        return obj;
    }

    // 点击左侧数据
    $('body').delegate(".list-left li", "click", function () {
        $(".list-left li").removeClass("layui-this")
        $(this).addClass("layui-this")
        var id = $(this).attr("data-id")
        var obj = layui.data("chatData", { key: id })
        $(".message").html("") //清空聊天内容
        msgUser("0", obj.greetings)
        layui.each(obj.data, function (k, v) {
            if (v.role == "assistant") { //机器人信息
                msgUser(`data${k}`, v.content)
            }
            if (v.role == "user") { //我的信息
                msgMine(v.content)
            }
        })
        BoxRoll()
    })

    //点击默认左侧列表第一个
    function onlistLeftOne() {
        $(".list-left li:first-child").click()
        BoxRoll()
    }

    onlistLeftOne()

    // 我说话事件
    form.on('submit(sendMsg)', function (data) {
        var field = data.field; // 获取表单字段值

        // layer.msg("asd")

        return false; // 阻止默认 form 跳转
    });

    // 提交事件
    form.on('submit(addAi)', function (data) {
        var field = data.field; // 获取表单字段值

        layui.data("chatData", {
            key: uuid(),
            value: {
                title: field.title,
                remark: field.remark,
                greetings: field.greetings,
                data: [
                    {
                        "content": field.system,
                        "id": "LEMUR_AI_SYSTEM_SETTING",
                        "isSensitive": false,
                        "needCheck": false,
                        "role": "system"
                    }
                ]
            }
        })
        // console.log(field)
        var data = layui.data("chatData");
        $('.list-left').html("")
        eachList(data)
        layer.closeAll()
        onlistLeftOne()

        return false; // 阻止默认 form 跳转
    });

    function BoxRoll() {
        if ($(".layui-card-body").scrollTop() + $(window).height() != $(".message").height()) {
            // $(".layui-card-body").animate({ scrollTop: $(".messages").prop("scrollHeight") }) //滚动条
            $(".layui-card-body").scrollTop($(".layui-card-body").scrollTop() + $(window).height())
        }
    }

    $("body").delegate(".more-btn", "click", function () {
        var then = $(this)
        var parent = $(this).parent()
        dropdown.render({
            elem: this, // 触发事件的 DOM 对象
            show: true, // 外部事件触发即显示
            data: [{
                title: '复制',
                id: 'copy'
            }, {
                title: '删除',
                id: 'del'
            }],
            click: function (menudata) {
                // console.log(menudata)
                if (menudata.id === 'copy') { //点击复制
                    // 创建一个 textarea 元素
                    var textArea = document.createElement('textarea');
                    if (parent.hasClass("msg-mine")) {
                        // 存在该 class，执行相应操作
                        var copyMsg = parent.find(".content").html()
                        textArea.value = copyMsg
                    } else {
                        // 不存在该 class，执行相应操作
                        var copyMsg = parent.find(".msg").html()
                        textArea.value = copyMsg
                    }
                    document.body.appendChild(textArea);
                    // 选中 textarea 中的所有文本
                    textArea.select()
                    try {
                        // 尝试执行复制操作
                        var success = document.execCommand('copy');
                        if (success) {
                            layer.msg('复制成功！');
                        } else {
                            layer.msg('复制失败！');
                        }
                    } catch (err) {
                        layer.msg('复制失败！', err);
                    }
                    // 最后移除 textarea 元素
                    document.body.removeChild(textArea);
                } else if (menudata.id === 'del') {
                    var key = $(".list-left .layui-this").attr("data-id")
                    var index = parent.index()
                    layer.confirm('确定删除该信息吗？', {
                        btn: ['确定', '关闭'] //按钮
                    }, function () {
                        if (index != 0) {
                            var data = layui.data("chatData", { key: key })
                            data.data.splice(index, 1)
                            layui.data("chatData", { key: key, value: data })
                            onlistLeftOne()
                            layer.closeAll();
                        } else {
                            layer.msg("该信息不可删除")
                        }
                    });
                }
            },
            align: 'center', // 右对齐弹出
        })
    })

    var textSize = layui.data("options", { key: "textSize" })
    if (textSize) {
        $(".content").css("font-size", textSize + "px")
        $(".content").css("line-height", (Number(textSize) + 6) + "px")
    }

    form.on('radio(textSize)', function (data) {
        // console.log(data);
        var size = data.value;
        var data = layui.data("options", { key: "textSize", value: size })
        $(".content").css("font-size", size + "px")
        $(".content").css("line-height", (Number(size) + 6) + "px")
    });

    //头部事件
    util.event('lay-event', {
        menuLeft: function (othis) { // 左侧菜单事件
            // layer.msg('展开左侧菜单的操作', { icon: 0 });
            var state = $(othis).attr("data-hide")
            if (state === "true") {
                $(".layui-logo").hide()
                $(".layui-side").hide()
                $(othis).html('<i class="layui-icon layui-icon-shrink-right"></i>')

                $(".layui-layout-left").animate({ left: 0 }, 500)
                $(".layui-body").animate({ left: 0 }, 500)
                $(".layui-footer").animate({ left: 0 }, 500)

                $(othis).attr("data-hide", "false")
            } else {
                $(".layui-logo").show()
                $(".layui-side").show()

                $(othis).html('<i class="layui-icon layui-icon-spread-left"></i>')
                $(".layui-layout-left").animate({ left: "200px" }, 0)
                $(".layui-body").animate({ left: "200px" }, 500)
                $(".layui-footer").animate({ left: "200px" }, 500)

                $(othis).attr("data-hide", "true")
            }

        },
        menuRight: function () {  // 右侧菜单事件
            var textSize = layui.data("options", { key: "textSize" })
            if (!textSize) {
                textSize = 14
            }
            addAiBox = layer.open({
                type: 1,
                title: '更多',
                content: `<div style="padding: 15px;">
                <p>字体大小</p>
                <div class="layui-form">
                    <input type="radio" name="textSize" value="14" title="默认" lay-filter="textSize" ${textSize == 14 ? 'checked' : ''}  >
                    <input type="radio" name="textSize" value="18" title="中" lay-filter="textSize" ${textSize == 18 ? 'checked' : ''} > 
                    <input type="radio" name="textSize" value="20" title="大" lay-filter="textSize" ${textSize == 20 ? 'checked' : ''} > 
                </div>
                </div>`,
                area: ['260px', '100%'],
                offset: 'rt', // 右上角
                anim: 'slideLeft', // 从右侧抽屉滑出
                shadeClose: true,
                scrollbar: false,
                success: function () {
                    form.render()
                }
            });
        },
        addAi: function () { //添加ai类型
            layer.open({
                type: 1, // page 层类型
                area: ['500px', '350px'],
                title: '添加AI类型',
                maxmin: true, // 允许全屏最小化
                content: `
                <form class="layui-form layui-form-pane" action="" style="padding:10px;">
                    <div class="layui-form-item">
                        <label class="layui-form-label">昵称</label>
                        <div class="layui-input-block">
                            <input type="text" name="title" autocomplete="off" placeholder="昵称" lay-verify="required" class="layui-input" value="AI助手">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">简介</label>
                        <div class="layui-input-block">
                            <input type="text" name="remark" autocomplete="off" placeholder="简介" lay-verify="required" class="layui-input"
                            value="解决通用问题" >
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">问候语</label>
                        <div class="layui-input-block">
                            <input type="text" name="greetings" autocomplete="off" placeholder="问候语" lay-verify="required" class="layui-input" 
                            value="你好，我是AI助手，请问您需要什么帮助？">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">角色指令</label>
                        <div class="layui-input-block">
                            <input type="text" name="system" autocomplete="off" placeholder="不填则为通用" class="layui-input" 
                            value="">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <button class="layui-btn" lay-submit lay-filter="addAi">确认</button>
                        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                    </div>
                </form>`
            })
        },
        delAI: function () { //删除ai类型
            var id = $(".list-left .layui-this").attr("data-id")
            var obj = layui.data("chatData", { key: id })

            layer.confirm('确定删除该对话信息吗？', {
                btn: ['确定', '关闭'] //按钮
            }, function () {
                if (typeof obj !== "undefined") {
                    layui.data("chatData", { key: id, remove: true })

                    var data = layui.data("chatData");
                    // console.log(data)

                    $('.list-left').html("")
                    default_chatData(data)

                    onlistLeftOne()

                } else {
                    layui.msg("没有选择AI类型，请选择~")
                }
                layer.closeAll();
            });
        },
        sendMsg: function () { //提交
            var content = $("#msg-content").val()
            var id = $(".list-left .layui-this")
            if (content.trim() == "") {
                layer.msg("请输入信息")
                return
            }
            if (!id.length) {
                layer.msg("请选择AI类型")
                return
            }
            // AI正在思考中...
            $("#msg-content").attr("disabled", true);
            $(".msg-header").find(".title").html("AI思考中...")

            msgMine(content)

            var obj = dataEdit(id.attr("data-id"), {
                content: content,
                isSensitive: false,
                needCheck: true,
                role: "user"
            })

            var msgData = obj.data;
            let i = 0;

            $.ajax({
                url: 'http://127.0.0.1:8788/',
                type: 'POST',
                data: { msg: msgData },
                contentType: 'application/octet-stream',
                xhrFields: {
                    onprogress: function (e) {
                        var strLength = (e.currentTarget.responseText).length;
                        if (i != strLength && strLength > 20) {

                            // gptStrJson((e.currentTarget.responseText).substring(i))

                            var obj = gptStrJson((e.currentTarget.responseText).substring(i));

                            layui.each(obj, function (k, v) { //循环打印
                                if (v.code == 0) {
                                    var data = gptStrObj(v.data);
                                    layui.each(data, function (kk, vv) {
                                        if (typeof vv.choices[0].delta.content !== "undefined") {
                                            $(".msg-header").find(".title").html("AI正在输入中...")
                                            msgUser(vv.id, vv.choices[0].delta.content);
                                        }
                                        if (typeof vv.choices[0].finish_reason !== "undefined" && vv.choices[0].finish_reason == "stop") {
                                            // 写入结束
                                            $("#msg-content").attr("disabled", false);
                                            $(".msg-header").find(".title").html("聊天内容")
                                            // 追加机器人数据
                                            var content = $(`#${vv.id}`).find(".msg").html()
                                            var id = $(".list-left .layui-this").attr("data-id")
                                            dataEdit(id, {
                                                content: content,
                                                isSensitive: false,
                                                needCheck: true,
                                                role: "assistant"
                                            })
                                        }
                                        debugger;
                                    })

                                } else {
                                    if (v.code == 401) {
                                        layer.msg("网络中断了")
                                    }
                                    // 写入结束
                                    $("#msg-content").attr("disabled", false);
                                    $(".msg-header").find(".title").html("聊天内容")
                                }
                            })

                            i = strLength
                        }
                    },
                },
                success: function (data) {
                    // console.log('成功接收到响应！', data);
                    // 写入结束
                    $("#msg-content").attr("disabled", false);
                    $(".msg-header").find(".title").html("聊天内容")
                },
                error: function (xhr, textStatus, errorThrown) {
                    // console.log('Error:', errorThrown);
                    layui.msg("网络错误")
                }
            });


        }
    });
});